package com.aizhixin.lab.docker.service;

import com.aizhixin.lab.docker.common.ExceptionValidation;
import com.aizhixin.lab.docker.domain.ChapterImagesDomain;
import com.aizhixin.lab.docker.domain.ChapterImagesDomainV2;
import com.aizhixin.lab.docker.entity.ChapterImages;
import com.aizhixin.lab.docker.repository.ChapterImagesRepository;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

@Slf4j
@Service
@Transactional
public class ChapterImagesService {
    @Autowired
    private ChapterImagesRepository chapterImagesRepository;

    public ChapterImages saveChapterImages(ChapterImagesDomain domain) {
        if (StringUtils.isEmpty(domain.getChapterId())) {
            throw new ExceptionValidation(417, "chapter id is null");
        }
        if (StringUtils.isEmpty(domain.getCourseId())) {
            throw new ExceptionValidation(417, "course id is null");
        }
        chapterImagesRepository.deleteAllByChapterId(domain.getChapterId());
        ChapterImages chapterImages = new ChapterImages();
        chapterImages.setCourseId(domain.getCourseId());
        chapterImages.setChapterId(domain.getChapterId());
        chapterImages.setImageName(domain.getImageName());
        chapterImages.setUserId(domain.getUserId());
        chapterImages.setNum(domain.getNum());
        chapterImages.setCreateDate(new Date());
        chapterImages.setExpire(domain.getExpire());
        chapterImages.setOverSold(domain.getOverSold());
        chapterImages.setSpec(domain.getSpec());
        chapterImages = chapterImagesRepository.save(chapterImages);
        return chapterImages;
    }

    public ChapterImagesDomainV2 findChapterId(Long chapterId) {
        ChapterImagesDomainV2 chapterImagesDomainV2 = new ChapterImagesDomainV2();
        ChapterImages chapterImages = chapterImagesRepository.findAllByChapterId(chapterId);
        if (chapterImages != null) {
            chapterImagesDomainV2.setName(chapterImages.getImageName());
            chapterImagesDomainV2.setNum(chapterImages.getNum());
            return chapterImagesDomainV2;
        } else {
            return null;
        }
    }

}
